import {get,set } from 'lodash';
const setCellType = (cell, toCell) => {
    const cellType = cell.cellType();
    if (cellType.typeName) {
        const CellTypeClass = window[cellType.typeName];
        if (CellTypeClass) {
            let cellTypeInstance = new CellTypeClass();
            cellTypeInstance.fromJSON(cellType);
            toCell.cellType(cellTypeInstance);
            if(cellType.vierAttr !=1)
            toCell.locked(false);
        }
    }
}

const getFieldName = (bindingPath) => {

    let strs = bindingPath.split(".");
    return strs[strs.length-1];

}

const getCurrentT = (bindingPath) => {

    let strs = bindingPath.split(".");
    return strs[2];

}

const setSameHeight = (sheet, form, to, downExpandspanRowCount) => {
    for(let i = 0 ; i < downExpandspanRowCount ; i++) {
        sheet.setRowHeight(to + i, sheet.getRowHeight(form + i));
    }
}


const relatedChildFun = (relatedChild, childValues, value, cellType, sheet, row, cellcol, cRow,rowCount) => {
    
    const cvalues = childValues ? childValues.split(",") : undefined;
    const expandType = cellType.expandType;
    // 横向扩展
    if(expandType == '1') {
        let colCount = 1;
        let startCol = cellcol;
        // 纵向扩展的合并单元格
        const span = sheet.getSpan(row, cellcol);
        if(span) {
            colCount = span.colCount;
            startCol = span.col;
        }
        // 横向扩展
        for(let rr = 0; rr < rowCount; rr++) {
            const r = cRow + rr;
            for(let c = 0 ; c < colCount; c++) {
                let colCol = startCol + c;
                
                const childCell = sheet.getCell(r, colCol);
                const cCelltype = childCell.cellType();
                // 获取到关联的子下拉框
                if(childCell.bindingPath() && cCelltype && cCelltype.typeName == 'WeaSelectCellType' 
                && getFieldName(childCell.bindingPath()) == relatedChild) {
                    let newItems = [];
                    if (cvalues) {
                        newItems = cCelltype.fieldType[2].datas.filter(r =>
                            cvalues.indexOf(r.selectName) > -1
                        );
                    } else if (value) {
                    } else {
                        // 父字段没有值，子字段也不能选
                        //newItems = cellType.fieldType[2].datas;
                    }

                    console.log(newItems,row, colCol);
                    if (newItems.length == 0 && childCell.value()) {
                        childCell.value(undefined);
                    } else {
                        if (newItems.filter(r => r.selectValue == childCell.value()).length < 1) {
                            if(childCell.value()) {
                                childCell.value(undefined);
                            }
                        }
                    }
                    cCelltype.items(newItems.map((d) => ({ text: d.selectName, value: '' + d.selectValue })));
                }
            }
            
        }
    }

}

export default {
    canUndo: true,
    execute: (context, options, isUndo) => {
        context.suspendPaint();
        try {
            const { table, store, row: currentRow,sheet, sheetName,oldDelete,insertType ,insertRowCount} = options;
            const bindingPath = table.bindingPath();
            if (isUndo) {
                const { name, row, col, rowCount, colCount, cellTypes, bindingPath, showHeader, cRow, insertRowCount,currentT,expandT,preBindPath} = options.old;
                const ct = store.customBindingCurrentT[preBindPath];
                const source = store.dataSourceInstance.getSource();
                for(let i = ct ; i > currentT ; i--) {
                    delete source[`${sheetName}`]["custom_" + table.name().substring("custom".length)][`${'t'+i}`];
                }
                sheet.deleteRows(cRow,insertRowCount);
                sheet.tables.resize(table,rowCount, colCount);

                options._oldSpan.forEach(range => {
                    sheet.addSpan(range.row, range.col, range.rowCount, range.colCount);
                });
                store.customBindingCurrentT[preBindPath] = currentT;
                store.customExpandCurrent[preBindPath] = expandT;
            } else {
                const {row, rowCount, col, colCount} = table.dataRange();
                let num = 0;
                let num1 = insertRowCount;
                if(insertType == 'bottom') {
                    num = insertRowCount;
                    num1 = 0;
                }

                const preBindPath = sheet.name() + ".custom_" + table.name().substring("custom".length);
                let currentT = store.customBindingCurrentT[preBindPath];
                let expandT = store.customExpandCurrent[preBindPath];
                options.old = {
                    name, row, col, rowCount, colCount, bindingPath,cRow:currentRow+ num,insertRowCount,currentT,expandT,preBindPath
                    
                };

                options._oldSpan = [];
                for(let r = 0 ; r < rowCount ; r++) {
                    const cr = r + row;
                    for(let c = 0 ; c <colCount ; c++) {
                        const cc = c + col;
                        const span = sheet.getSpan(cr, cc);
                        if(span && cr == span.row && cc == span.col) {
                            options._oldSpan.push(span);
                        }
                    }
                }

                // 先resize再赋值
                sheet.addRows(currentRow+ num,insertRowCount );
                sheet.tables.resize(table,rowCount+insertRowCount, colCount);

                const beforespans = [];
                const tmpr = Number(currentRow) + num1;
                for(let c = 0 ; c < colCount; c++) {
                    const cc = c+ col;
                    const span = sheet.getSpan(tmpr,cc);
                    if(span && span.rowCount > insertRowCount) {
                        beforespans.push(span)
                        sheet.removeSpan(tmpr,cc);
                    }
                }

                sheet.copyTo(Number(currentRow) + num1, col, Number(currentRow) + num, col, insertRowCount, colCount, GC.Spread.Sheets.CopyToOptions.all);

                setSameHeight(sheet, Number(currentRow) + num1, Number(currentRow) + num, insertRowCount);
                if(beforespans.length > 0) {
                    beforespans.forEach(span => {

                        sheet.addSpan(span.row < Number(currentRow) + num ? span.row : Number(currentRow) + num, 
                        span.col, span.row < Number(currentRow) + num ?span.rowCount : span.rowCount + insertRowCount, span.colCount);
                    })
                }
                // 新增块首行
                const startRow = Number(currentRow) + num;
                const downlist = [];
                const celllist = [];
                const samedownlist = [];
                const samecelllist = [];
                const downColNum = [];
                const spans =[];
                // 逐个绑定
                for(let i = 0 ; i < colCount ; i++) {
                    const cCol = col + i;
                    const span = sheet.getSpan(startRow, cCol);
                    // 合并单元格且跟新增长度一样
                    if(span && span.rowCount == insertRowCount) {
                        const cell = sheet.getCell(span.row, span.col);
                        const cellType = cell.cellType();

                        if(cellType) {
                            // 纵向扩展清空
                            if(cellType.expandType =='2') {
                                expandT = expandT + 1;
                                cell.bindingPath(preBindPath+'h'+".t" + expandT +"."+ getFieldName(cell.bindingPath()));
                                setCellType(sheet.getCell(currentRow,cCol),cell);
                                downlist.push(getFieldName(cell.bindingPath()));
                                celllist.push(cell);
                                downColNum.push(cCol);
                                spans.push(span);
                                continue;
                            }

                        }

                    } else if(span && span.rowCount > insertRowCount) {
                        // 长度大于的，新增列该值不变
                    } else if(insertRowCount == 1) {
                        const cell = sheet.getCell(startRow, cCol);
                        const cellType = cell.cellType();

                        if(cellType) {
                            // 纵向扩展清空
                            if(cellType.expandType =='2') {
                                expandT = expandT + 1;
                                cell.bindingPath(preBindPath+'h'+".t" + expandT +"."+ getFieldName(cell.bindingPath()));
                                setCellType(sheet.getCell(currentRow,cCol),cell);
                                downlist.push(getFieldName(cell.bindingPath()));
                                celllist.push(cell);
                                downColNum.push(cCol);
                                continue;
                            }

                        }
                    }

                    for(let j = 0 ; j < insertRowCount; j++ ) {
                        const cRow =  startRow + j;
                        const cell = sheet.getCell(cRow, cCol);
                        const cellType = cell.cellType();
                        if(cellType && cellType.expandType !='2') {
                            if(j == 0) {
                                currentT = currentT + 1;
                                store.dataSourceInstance.setValue(preBindPath+".t" + currentT,JSON.parse(JSON.stringify(store.dataSourceInstance.getValue(preBindPath+"." + getCurrentT(sheet.getCell(currentRow,cCol).bindingPath())))));
                                downlist.forEach(fieldname => {
                                    store.dataSourceInstance.setValue((preBindPath+".t" + currentT+"."+ fieldname),'');
                                })
                            }
                            
                            store.dataSourceInstance.setValue((preBindPath+".t" + currentT+"."+ getFieldName(cell.bindingPath())),'');
                            cell.bindingPath(preBindPath+".t" + currentT +"."+ getFieldName(cell.bindingPath()));
                            setCellType(sheet.getCell(currentRow + j,cCol),cell);
                        }
                    }
                    
                }
                celllist.forEach(cell => {
                    cell.value(undefined);
                })
                // 新增行后，有时候span不起作用，此处对span再设置下

                for(let r = startRow ; r < row + rowCount ; r = r + insertRowCount) {
                    for(let i = 0 ; i < downColNum.length; i++) {

                        const span = sheet.getSpan(r, downColNum[i]);
                        if(!span) {
                            const s = spans[i];
                            if(s)
                            sheet.addSpan(r, downColNum[i],s.rowCount, s.colCount);
                        }
                    }
                }
                store.customBindingCurrentT[preBindPath] = currentT;
                store.customExpandCurrent[preBindPath] = expandT;
                // 横向的需要处理下，处理联动情况
                const {row:tablerow, rowCount:tablerowCount, col:tablecol, colCount:tablecolCount} = table.dataRange();
                for (let r = 0; r < tablerowCount; r++) {
                    const row = tablerow + r;
                    for (let c = tablecol; c < tablecol + tablecolCount; c++) {
                        const col = c;
                        let cell;
                        const span = sheet.getSpan(row,col);
                        if(span) {
                            cell = sheet.getCell(span.row, span.col);
                        } else {
                            cell = sheet.getCell(row, col);
                        }
                        
                        const cellType = cell.cellType();
                        const newValue = cell.value();
                        if (cellType && cellType.expandType == '1') {
                            const filedType = cellType.fieldType;
                            if (filedType && filedType[2]) {
                                const relatedChild = filedType[2].relatedChild;
                                const datas = filedType[2].datas;


                                if (relatedChild) {
                                    // 下拉框选择的值
                                    const selectValue = datas.filter(r => r.selectValue == newValue)[0];
                                    // 选择框有值时
                                    if (selectValue && newValue) {

                                        relatedChildFun(relatedChild, selectValue.childValue, newValue, cellType, sheet, row, col, currentRow + num,insertRowCount);
                                    } else {
                                        relatedChildFun(relatedChild, undefined, undefined, cellType, sheet, row, col, currentRow + num,insertRowCount);
                                    }
                                }
                            }
                        }

                    }
                }
            }


            // table.bindingPath(bindingPath);
            // store.calcAll(true, sheetName);
        } catch (e) {
            if (!!(window.console && window.console.log)) {
                window.console.log(e);
            }
        }
        context.resumePaint();
    }
};